package vn.mobiistar.videoapp.fragment;

import java.util.ArrayList;

import vn.appsmobi.loader.Pager;
import vn.mobiistar.videoapp.R;
import vn.mobiistar.videoapp.activity.MainActivity;
import vn.mobiistar.videoapp.loader.BaseResult;
import vn.mobiistar.videoapp.loader.VideoLoader;
import vn.mobiistar.videoapp.other.Define;
import vn.mobiistar.videoapp.other.Video;
import vn.mobiistar.videoapp.other.VideoPlayer;
import vn.mobiistar.videoapp.ui.BlockView;
import vn.mobiistar.videoapp.ui.Refreshable;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.github.pedrovgs.DraggablePanel;

public class SearchFragment extends BaseFragment implements
		LoaderCallbacks<BaseResult>, Refreshable {
	private static final String SAVE_AUTOCOMPLETE_SEARCH = "searchfragment_save_autocomplete_search";
	private static final String SPLIT_SIGN = "MBS";
	private static final long DELAY_INPUT_PRESS = 1000;
	private View content;
	public Context mContext;
	public ArrayList<Video> mData;
	public String[] mLastSearchStringArrayFilter;
	public boolean mIsReachedBottom;
	protected VideoLoader mLoader;
	private BlockView mBlock;
	private static String TAG = "SearchFragment";
	public boolean mIsInitLoader = false;
	private AbsListView.OnScrollListener mOnScrollListener = new Pager(
			new Runnable() {
				@Override
				public void run() {
					if ((SearchFragment.this.mLoader != null)
							&& (!SearchFragment.this.mLoader.isLoading())
							&& (!SearchFragment.this.mIsReachedBottom)) {
						// fix bug
						if (mPlayer.getYoutubePlayer() != null)
							if (!mPlayer.isPlaying())
								draggablePanel.setVisibility(View.GONE);

						((VideoLoader) SearchFragment.this.mLoader).nextPage();
						((VideoLoader) SearchFragment.this.mLoader).forceLoad();
					}
				}
			});
	public SharedPreferences mSharePre;
	public Editor mEditor;
	private ArrayAdapter<String> mLastSearchAdapter;
	private String[] mLastSearchStringArray;
	protected boolean mPositionAutoCompleteClick;
	private ListView mLastSearch;
	private CharSequence mKeyword;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreateView(inflater, container, savedInstanceState);
		content = inflater.inflate(R.layout.fragment_search, null);

		Display display = ((WindowManager) getActivity().getSystemService(
				Context.WINDOW_SERVICE)).getDefaultDisplay();
		mRotation = display.getRotation();
		// click xem video
		ListView.OnItemClickListener loi = new ListView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				onVideoClick(parent, view, position, id);
			}
		};
		mContext = getActivity();
		draggablePanel = (DraggablePanel) content
				.findViewById(R.id.fs_draggable_panel);
		((MainActivity)mContext).navSearchRemoveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				((MainActivity)mContext).navSearchText.setText("");
				mData.clear();
			}
		});
		mLastSearch    = (ListView) content.findViewById(R.id.fs_lastsearch);
		mPlayer = new VideoPlayer(mContext, this, draggablePanel);
		((MainActivity) getActivity()).currentFragment = this;
		mBlock = new BlockView(mContext, null);
		mBlock.switchToScrollMode();
		mBlock.getList().setOnScrollListener(mOnScrollListener);
		mBlock.setmMgs(getResources().getString(R.string.search_hint2));
		mBlock.getList().setOnItemClickListener(loi);
		LinearLayout ll_root = (LinearLayout) content
				.findViewById(R.id.fs_blockcontain);
		ll_root.addView(mBlock);
		
		mData = new ArrayList<Video>();
		mLoader = new VideoLoader(mContext);
		((VideoLoader) mLoader).setType(Define.BLOCK_TYPE_KEYWORD);

		// auto complete text search
		mSharePre = getActivity().getPreferences(Activity.MODE_WORLD_WRITEABLE);
		mEditor = mSharePre.edit();
//		 mEditor.putString(SAVE_AUTOCOMPLETE_SEARCH, "anh khangMBSbao thyMBSBang kieuMBSDan NguyenMBSDam VInh HungMBSPham Quynh AnhMBSSon Tung MTP");
//		 mEditor.putString(SAVE_AUTOCOMPLETE_SEARCH, "");
//		 mEditor.commit();
		
		initLastSearchListView();
		
		((MainActivity) getActivity()).navSearchText.addTextChangedListener(new TextWatcher() {
			public CharSequence currentKeyword;
			@Override
			public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
				// hien thi autocomplete
				mLastSearch.setVisibility(View.VISIBLE);
				if (s.length() == 0){
					restoreKeyword();
				}
				// filter autocomplete
				filterKeyword(s.toString());
				
				// neu tu khoa lon hon 3 ky tu thi bat dau tim kiem
				if (s.length() >= 3){
					currentKeyword = s;
					Handler handler = new Handler();
					Runable run = new Runable();
					run.initLeng = currentKeyword.length();
			        handler.postDelayed(run, DELAY_INPUT_PRESS);
				}
			}
			@Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {}
			@Override public void afterTextChanged(Editable arg0) {}
			class Runable implements Runnable{
				public int initLeng;
				@Override
				public void run() {
					// TODO tai thoi diem run khoi chay.
					if(initLeng == currentKeyword.length()) {
						Log.i(TAG, " tien hanh tim kiem vi nguoi dung da ngung nhap ");
						search(currentKeyword);
					}
					else{
						Log.i(TAG, "Nguoi dung dang tiep tuc bam");
					}
				}

			}
		});
				
		return content;
	}
	
	// hien thi autocomplete duoc loc voi keyword
	public void filterKeyword(String keyword){
		mBlock.setVisibility(View.GONE);
		int j = 0;
		String[] tmp = new String[mLastSearchStringArray.length];
		if(mLastSearchStringArray != null) if(mLastSearchStringArray.length >0) for (int i = 0; i < mLastSearchStringArray.length; i++) {
			// neu tim thay
			if(mLastSearchStringArray[i].toLowerCase().indexOf(keyword.toLowerCase()) != -1){
				tmp[j] = mLastSearchStringArray[i];
				j++;
			}
		}
		mLastSearchStringArrayFilter = new String[j];
		for (int i = 0; i < j; i++) {
			mLastSearchStringArrayFilter[i] = tmp[i];
		}
		
		mLastSearchAdapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_list_item_1, mLastSearchStringArrayFilter);
		mLastSearch.setAdapter(mLastSearchAdapter);
		
		mLastSearch.setVisibility(View.VISIBLE);
	}
	
	// hien thi day du autocomplete
	public void restoreKeyword(){
		mLastSearchAdapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_list_item_1, mLastSearchStringArray);
		mLastSearch.setAdapter(mLastSearchAdapter);
		
		mLastSearch.setVisibility(View.VISIBLE);
	}
	
	// lay ve danh sach nhung tu da tim kiem truoc day
	public void initLastSearchListView(){
		mLastSearchStringArray = mSharePre.getString(SAVE_AUTOCOMPLETE_SEARCH, "")
				.split(SPLIT_SIGN);

		mLastSearchAdapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_list_item_1, mLastSearchStringArray);
		mLastSearch.setAdapter(mLastSearchAdapter);
		
		// khi click vao keyword o listview autocomplete
		mLastSearch.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				String s = mLastSearchAdapter.getItem(position).toString();
				Log.i(TAG, s.toString()+"keyword clicked");
				((MainActivity)getActivity()).navSearchText.setText(s);
				mPositionAutoCompleteClick = true;
			}
		});
	}
	
	// tim kiem tren server
	public void search(CharSequence s) {
		mKeyword = s;
		mLastSearch.setVisibility(View.GONE);
		mBlock.setVisibility(View.VISIBLE);
		mData.clear();
		mLoader.setKeyword(s.toString());
		Log.i(TAG, "search with "+s.toString());
		if (!mIsInitLoader) {
			Log.i(TAG, "init loader");
			SearchFragment.this.getLoaderManager().initLoader(
					Define.BLOCK_TYPE_KEYWORD, null,
					SearchFragment.this);
			mIsInitLoader = true;
		} else {
			Log.i(TAG, "force load");
			mLoader.reload();
		}
	}
        
	// kiem tra xem keyword da co trong shareprefercence
	public boolean isReadyInStringKeyword(String str) {
		if (mSharePre.getString(SAVE_AUTOCOMPLETE_SEARCH, "").length() == 0)
			return false;
		if (mSharePre.getString(SAVE_AUTOCOMPLETE_SEARCH, "").lastIndexOf(str) == -1)
			return false;
		return true;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public Loader<BaseResult> onCreateLoader(int id, Bundle arg1) {
		mLoader.setProgressNotifiable(mBlock.getLoadingView());
		if (id == Define.BLOCK_TYPE_KEYWORD)
			return mLoader;
		return null;
	}

	@Override
	public void onLoadFinished(Loader<BaseResult> loader,
			final BaseResult result) {
		// TODO Auto-generated method stub
		final int id = loader.getId();
		((MainActivity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (id == Define.BLOCK_TYPE_KEYWORD)
					if (((VideoLoader.Result) result).mVideo != null)
						if (((VideoLoader.Result) result).mVideo.size() > 0) {
							mData = ((VideoLoader.Result) result).mVideo;
							mBlock.setVisibility(View.VISIBLE);
							mBlock.setData(mData);
							mBlock.unsetMsg();
							mLastSearch.setVisibility(View.GONE);
							// neu la click tu listview auto complete
							if (mPositionAutoCompleteClick == false && !isReadyInStringKeyword(mKeyword.toString())) {
								// luu vao danh sach nhung tu khoa
								if(mSharePre.getString(SAVE_AUTOCOMPLETE_SEARCH,"")==""){
									mEditor.putString(
											SAVE_AUTOCOMPLETE_SEARCH,
											mSharePre.getString(SAVE_AUTOCOMPLETE_SEARCH,"")
												 + mKeyword);
								}else{
									mEditor.putString(
											SAVE_AUTOCOMPLETE_SEARCH,
											mSharePre.getString(SAVE_AUTOCOMPLETE_SEARCH,"")
													+ SPLIT_SIGN + mKeyword);
								}
								mEditor.commit();
								initLastSearchListView();
							}
						} else {
							mIsReachedBottom = true;
							if (mData.size() == 0)
								mBlock.setmMgs(getResources().getString(
										R.string.search_no_record));
						}
			}
		});
	}

	@Override
	public void onLoaderReset(Loader<BaseResult> arg0) {
	}

	@Override
	public void refreshData() {
	}
}
